<?php

declare(strict_types=1);

namespace app\controller\system;

use app\BaseController;
use app\service\system\UserService;
use owns\exception\TransException;

/**
 * 管理员
 */
class User extends BaseController
{
    protected $userService;

    public function initialize()
    {
        $this->userService = make(UserService::class);
    }
    /**
     * 角色列表
     */
    public function list()
    {
        return $this->success($this->userService->list($this->paging()));
    }
    /**
     * 管理员编辑
     */
    public function edit()
    {
        $data = $this->request->post();
        $this->validate($data, [
            'username' => 'require|length:2,20',
            //'password' => 'require|length:6,32',
            'phone' => 'require|length:11,16',
            'group_id' => 'require|integer|egt:1',
            'role_id' => 'require|integer|egt:1',
            'status' => 'integer|in:0,1',
        ]);
        return TransException::exec(UserService::class, 'edit', $data, (int) $data['id']);
    }
    /**
     * 重置密码
     */
    public function resetPassword()
    {
        $param = $this->request->post();
        $this->validate($param, [
            'password' => 'require|length:6,32',
            'encryption' => 'require|length:6,32',
            'ids' => 'array',
        ]);
        if (!$param['ids']) {
            return $this->error('无管理员信息');
        }
        return $this->userService->resetPassword($param) ? $this->success() : $this->error();
    }
    /**
     * 删除
     */
    public function delete()
    {
        $userId = $this->request->post('id');
        $res = $this->userService->delete((int) $userId);
        return $res ? $this->success() : $this->error();
    }
    /**
     * 修改状态
     */
    public function status()
    {
        $userId = $this->request->put('id');
        $res = $this->userService->status((int) $userId);
        return $this->success();
    }
    /**
     * 修改密码
     */
    public function modifyPassword()
    {
        $param = $this->request->put();
        $this->validate($param, [
            'userPassword|当前密码' => 'require|length:6,32',
            'newPassword|新密码（6~32字符）' => 'require|length:6,32',
            'confirmNewPassword|确认新密码（6~32字符）' => 'require|length:6,32',
        ]);
        return $this->userService->modifyPassword($param) ? $this->success() : $this->error();
    }
    /**
     * 修改个人信息
     */
    public function modifyUser()
    {
        $param = $this->request->put();
        $this->validate($param, [
            'nickname|昵称（1~10字符）' => 'require|length:1,10',
            'sex|性别' => 'require|in:0,1,2',
            'email|邮箱地址' => 'require|length:0,40',
            'signed|个人签名' => 'length:0,90',
        ]);
        return $this->userService->modifyUser($param) ? $this->success() : $this->error();
    }
}
